//
//  CommodityManagementVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/2/21.
//  Copyright © 2020 cat. All rights reserved.
//

#import "CommodityManagementVC.h"
#import "SPPageMenu.h"
#import "CommodityCell.h"
#import "CommodityModel.h"
#import "AddCommodityVC.h"
#import "EditStockVC.h"
#import "CommodityDetailVC.h"
#import "AddGoodsVC.h"
#import "OutsideGoodsDetailVC.h"
#import "YBAlertActionSheet.h"
#import "PlatformGoodsVC.h"

@interface CommodityManagementVC ()<SPPageMenuDelegate,UITableViewDelegate,UITableViewDataSource>{
    int pageIndex;
    
    NSInteger currentIndex;
}
@property (nonatomic, strong) SPPageMenu *pageMenu;
@property (nonatomic, strong) UITableView *commodityTable;
@property (nonatomic, strong) NSString *typeStr;

@property (nonatomic, strong) NSMutableArray *listArr;
@property (nonatomic, strong) YBAlertActionSheet *actionSheet;
@end

@implementation CommodityManagementVC
#pragma mark-------卖家获取商品分类下商品总数------------
-(void)requstGoodNum{
    NSString *url = [purl stringByAppendingFormat:@"?service=Seller.getGoodsNums"];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken]
                            };
    
    [WYNetworking postWithUrl:@"Seller.getGoodsNums" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            NSDictionary *infos = [info firstObject];
            NSString *onexamine =[NSString stringWithFormat:@"%@ %@",YZMsg(@"在售"), minstr([infos valueForKey:@"onsale"])];
            NSString *onsale =[NSString stringWithFormat:@"%@ %@",YZMsg(@"审核"), minstr([infos valueForKey:@"onexamine"])];
            NSString *remove_shelves =[NSString stringWithFormat:@"%@ %@",YZMsg(@"已下架"),minstr([infos valueForKey:@"remove_shelves"])];
            NSString *saleother =[NSString stringWithFormat:@"%@ %@",YZMsg(@"代卖"),minstr([infos valueForKey:@"platform"])];

            [_pageMenu setSelectedItemIndex:currentIndex];
            [_pageMenu setContent:onexamine forItemAtIndex:0];
            [_pageMenu setContent:saleother forItemAtIndex:1];
            [_pageMenu setContent:onsale forItemAtIndex:2];
            [_pageMenu setContent:remove_shelves forItemAtIndex:3];

        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}
#pragma mark-------获取商品列表------------
-(void)getGoodsList{
    NSString *url = [purl stringByAppendingFormat:@"?service=Seller.getGoodsList"];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"type":_typeStr,
                          @"p":@(pageIndex)
                            };
    
    [WYNetworking postWithUrl:@"Seller.getGoodsList" Dic:dic Suc:^(int code, id info, NSString *msg) {
        [self.commodityTable.mj_header endRefreshing];
        [self.commodityTable.mj_footer endRefreshing];
        if (code ==0) {
            NSArray *infos = info;
            if (pageIndex == 1) {
                [self.listArr removeAllObjects];
                if (infos.count < 1) {
                    [PublicView showImgNoData:self.commodityTable name:@"shop_无数据" text:YZMsg(@"你还没有相关商品")];
                    [self.commodityTable reloadData];
                    return ;
                }else{
                    [PublicView hiddenImgNoData:self.commodityTable];
                }

            }
            [self.listArr addObjectsFromArray:infos];
            [self.commodityTable reloadData];
        }else{
            [MBProgressHUD showError:msg];
        }
    } Fail:^(id fail) {
        [self.commodityTable.mj_header endRefreshing];
        [self.commodityTable.mj_footer endRefreshing];
    }];
}
#pragma mark-------获取代卖商品------------
-(void)getSaleOtherGoods{
//    NSString *url = [purl stringByAppendingFormat:@"?service=Seller.getOnsalePlatformGoods"];
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];
    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign,
                          @"p":@(pageIndex)
                          };
    
    [WYNetworking postWithUrl:@"Seller.getOnsalePlatformGoods" Dic:dic Suc:^(int code, id info, NSString *msg) {
        [self.commodityTable.mj_header endRefreshing];
        [self.commodityTable.mj_footer endRefreshing];
        if (code ==0) {
            NSArray *infos = info;
            if (pageIndex == 1) {
                [self.listArr removeAllObjects];
                if (infos.count < 1) {
                    [PublicView showImgNoData:self.commodityTable name:@"shop_无数据" text:YZMsg(@"你还没有相关商品")];
                    [self.commodityTable reloadData];
                    return ;
                }else{
                    [PublicView hiddenImgNoData:self.commodityTable];
                }

            }
            [self.listArr addObjectsFromArray:infos];
            [self.commodityTable reloadData];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            [self.commodityTable.mj_header endRefreshing];
            [self.commodityTable.mj_footer endRefreshing];

     }];

}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text = YZMsg(@"商品管理");
    self.view.backgroundColor = UIColor.whiteColor;
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    pageIndex = 1;
    currentIndex = 0;
    _typeStr = @"onsale";
    self.listArr = [NSMutableArray array];

    [self requstGoodNum];
    [self getGoodsList];
    _pageMenu = [SPPageMenu pageMenuWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, 40) trackerStyle:SPPageMenuTrackerStyleLineAttachment];
    _pageMenu.backgroundColor = RGB(235, 235, 235);
    _pageMenu.delegate = self;
    _pageMenu.dividingLine.hidden = YES;
    _pageMenu.selectedItemTitleColor = [UIColor blackColor];
    _pageMenu.itemTitleFont = [UIFont systemFontOfSize:12];
    _pageMenu.unSelectedItemTitleColor = [UIColor grayColor];
    _pageMenu.selectedItemTitleFont =  [UIFont systemFontOfSize:14];
    _pageMenu.unSelectedItemTitleFont = [UIFont systemFontOfSize:14];
    _pageMenu.permutationWay = SPPageMenuPermutationWayNotScrollEqualWidths;
    _pageMenu.tracker.backgroundColor = Pink_Cor;
    [self.view addSubview:_pageMenu];
    [self.view addSubview:self.commodityTable];
    
    [self bottomView];
    NSArray *arr = @[YZMsg(@"在售"),YZMsg(@"代卖"),YZMsg(@"审核"),YZMsg(@"已下架")];
    [_pageMenu setItems:arr selectedItemIndex:0];
}
- (void)pageMenu:(SPPageMenu *)pageMenu itemSelectedAtIndex:(NSInteger)index {
    currentIndex = index;
    switch (index) {
        case 0:
            _typeStr = @"onsale";
            [self.commodityTable.mj_header beginRefreshing];

            break;
        case 1:
            _typeStr = @"saleother";
            pageIndex = 1;
            [self getSaleOtherGoods];
            break;
        case 2:
            _typeStr = @"onexamine";
            [self.commodityTable.mj_header beginRefreshing];

            break;
        case 3:
            _typeStr = @"remove_shelves";
            [self.commodityTable.mj_header beginRefreshing];

            break;

        default:
            break;
    }
}
-(void)bottomView{
    UIView *back = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height-60, _window_width, 60)];
    back.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:back];
    
    UIButton *addBtn = [UIButton buttonWithType:0];
    addBtn.frame = CGRectMake(16, 10, _window_width-32, 40);
    [addBtn setBackgroundColor:Pink_Cor];
    [addBtn setTitle:YZMsg(@"添加商品") forState:0];
    addBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    addBtn.layer.cornerRadius = 5;
    addBtn.layer.masksToBounds = YES;
    [addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [back addSubview:addBtn];
}

-(UITableView *)commodityTable{
    if (!_commodityTable) {
        _commodityTable = [[UITableView alloc]initWithFrame:CGRectMake(0, _pageMenu.bottom, _window_width, _window_height-64-statusbarHeight-40-60) style:UITableViewStylePlain];
        _commodityTable.delegate = self;
        _commodityTable.dataSource = self;
        _commodityTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _commodityTable.backgroundColor = UIColor.whiteColor;
        _commodityTable.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
            if ([_typeStr isEqual:@"saleother"]) {
                pageIndex = 1;
                [self getSaleOtherGoods];

            }else{
                pageIndex = 1;
                [self getGoodsList];

            }
        }];
        _commodityTable.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
            if ([_typeStr isEqual:@"saleother"]) {
                pageIndex ++;
                [self getSaleOtherGoods];
            }else{
                pageIndex ++;
                [self getGoodsList];

            }
        }];
    }
    return _commodityTable;
}
#pragma mark-------tableviewDelegate-------------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 170;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YBWeakSelf;
    CommodityCell *cell = [CommodityCell cellWithTab:tableView andIndexPath:indexPath];
    CommodityModel *models = [[CommodityModel alloc]initWithDictionary:self.listArr[indexPath.row]];
    models.typeStr = _typeStr;
    cell.model = models;
    cell.btnEvent = ^(NSString * _Nonnull titles, CommodityModel * _Nonnull models) {
        if ([titles isEqual:YZMsg(@"删除")]) {
            [weakSelf deleteCommodity:models.idStr];
        }else if ([titles isEqual:YZMsg(@"上架")]){
            [weakSelf upOrDownType:@"1" status:models.idStr];
        }else if ([titles isEqual:YZMsg(@"下架")]){
            [weakSelf upOrDownType:@"-1" status:models.idStr];

        }else if ([titles isEqual:YZMsg(@"编辑")]){
            [weakSelf editGoods:models.idStr andType:models.type];
        }else if ([titles isEqual:YZMsg(@"价格与库存")]){
            
            EditStockVC *edit = [[EditStockVC alloc]init];
            edit.model = models;
            edit.reloadEvent = ^{
                [weakSelf.commodityTable.mj_header beginRefreshing];
            };
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:edit animated:YES];
        }else if ([titles isEqual:YZMsg(@"取消代卖")]){
            [weakSelf cancleSaleGoods:models.idStr];
        }
    };
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CommodityModel *models = [[CommodityModel alloc]initWithDictionary:self.listArr[indexPath.row]];

    [PublicObj checkGoodsExistenceWithID:models.idStr Existence:^(int code, NSString *msg) {
        if (code == 0) {
            if (_pageMenu.selectedItemIndex == 1) {
                CommodityDetailVC *detail = [[CommodityDetailVC alloc]init];
                detail.goodsID = models.idStr;
//                detail.fromWhere = @"seller";
                detail.liveUid = [Config getOwnID];
                [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

            }else{
                if ([models.type isEqual:@"1"]) {
                    OutsideGoodsDetailVC *detail = [[OutsideGoodsDetailVC alloc]init];
                    detail.goodsID = models.idStr;
                    detail.fromWhere = @"seller";
                    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

                }else if ([models.type isEqual:@"2"]){
                    OutsideGoodsDetailVC *detail = [[OutsideGoodsDetailVC alloc]init];
                    detail.goodsID = models.idStr;
                    detail.liveUid = [Config getOwnID];
                    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];

                } else{
                    CommodityDetailVC *detail = [[CommodityDetailVC alloc]init];
                    detail.goodsID = models.idStr;
                    detail.fromWhere = @"seller";
                    detail.liveUid = [Config getOwnID];
                    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:detail animated:YES];
                }

            }
            

        }else{
            [MBProgressHUD showError:msg];

        }
    }];

}
#pragma mark------取消代卖---------
-(void)cancleSaleGoods:(NSString *)goodsId{
    
    YBWeakSelf;

    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:nil message:YZMsg(@"确定取消代卖该商品？") preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *url = [purl stringByAppendingFormat:@"?service=Seller.setPlatformGoods"];
        NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
        NSString *sign = [PublicObj sortString:signdic];
        NSDictionary *dic = @{
                              @"uid":[Config getOwnID],
                              @"token":[Config getOwnToken],
                              @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                              @"goodsid":goodsId,
                              @"sign":sign,
                              };
        
        [WYNetworking postWithUrl:@"Seller.setPlatformGoods" Dic:dic Suc:^(int code, id info, NSString *msg) {
            if (code ==0) {
                [weakSelf getSaleOtherGoods];
            }else{
                [MBProgressHUD showError:msg];
            }
            [weakSelf requstGoodNum];

            } Fail:^(id fail) {
                
         }];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }] ;
    [sureAction setValue:Pink_Cor forKey:@"_titleTextColor"];
    [cancelAction setValue:[UIColor grayColor] forKey:@"_titleTextColor"];
    [alertControl addAction:sureAction];
    [alertControl addAction:cancelAction];
    [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:alertControl animated:YES completion:nil];
    
    

}
-(void)addBtnClick{
    YBWeakSelf;
    NSArray *arr = @[YZMsg(@"平台商品"),YZMsg(@"站内商品"),YZMsg(@"站外商品")];
    
    if ([PublicObj isUp]) {
        arr = @[YZMsg(@"平台商品"),YZMsg(@"编辑新商品")];
    }
    
    _actionSheet = [[YBAlertActionSheet alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height) cancelTitle:YZMsg(@"取消") cancelColor:[UIColor blackColor]  andRowHeight:50 andOtherTitle:arr];
    
    _actionSheet.btnEvent = ^(NSString *btnTitle) {
        NSString *titleStr = btnTitle;
        if ([titleStr isEqual:YZMsg(@"取消")]) {
            [weakSelf.actionSheet removeFromSuperview];
            weakSelf.actionSheet = nil;
        }else if ([titleStr isEqual:YZMsg(@"站内商品")] || [titleStr isEqual:YZMsg(@"编辑新商品")]) {
            [weakSelf.actionSheet removeFromSuperview];
            weakSelf.actionSheet = nil;

            AddCommodityVC *add = [[AddCommodityVC alloc]init];
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:add animated:YES];
        }else if ([titleStr isEqual:YZMsg(@"站外商品")]) {
            [weakSelf.actionSheet removeFromSuperview];
            weakSelf.actionSheet = nil;

            AddGoodsVC *vc = [[AddGoodsVC alloc]init];
            [[YBBaseAppDelegate sharedAppDelegate] pushViewController:vc animated:YES];
        }else if ([titleStr isEqual:YZMsg(@"平台商品")]) {
            [weakSelf.actionSheet removeFromSuperview];
            weakSelf.actionSheet = nil;

            PlatformGoodsVC *platgoods = [[PlatformGoodsVC alloc]init];
            [[YBBaseAppDelegate sharedAppDelegate] pushViewController:platgoods animated:YES];
        }
    };
    [self.view addSubview:_actionSheet];
}

#pragma mark------删除商品--------
-(void)deleteCommodity:(NSString *)goodsId{
    YBWeakSelf;
    UIAlertController *deleteAlert = [UIAlertController alertControllerWithTitle:YZMsg(@"确定删除商品?") message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *url = [purl stringByAppendingFormat:@"?service=Seller.delGoods"];
        NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
        NSString *sign = [PublicObj sortString:signdic];

        NSDictionary *dic = @{
                              @"uid":[Config getOwnID],
                              @"token":[Config getOwnToken],
                              @"goodsid":goodsId,
                              @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                              @"sign":sign
                                };
        
        [WYNetworking postWithUrl:@"Seller.delGoods" Dic:dic Suc:^(int code, id info, NSString *msg) {
            if (code ==0) {
                [MBProgressHUD showError:msg];
                [weakSelf.commodityTable.mj_header beginRefreshing];
                [weakSelf requstGoodNum];

            }else{
                [MBProgressHUD showError:msg];
            }

            } Fail:^(id fail) {
                
         }];

    }];
    [sureAction setValue:Pink_Cor forKey:@"_titleTextColor"];
    [cancelAction setValue:[UIColor blackColor] forKey:@"_titleTextColor"];

    [deleteAlert addAction:cancelAction];
    [deleteAlert addAction:sureAction];
    [self presentViewController:deleteAlert animated:YES completion:nil];
}


#pragma mark------上架、下架----------
-(void)upOrDownType:(NSString *)type status:(NSString*)goodsId{
    
    YBWeakSelf;
    NSString *status;
    if ([type isEqual:@"1"]) {
        status =YZMsg(@"确定上架商品?");
    }else{
        status =YZMsg(@"确定下架商品?");
    }
    
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:status message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        NSString *url = [purl stringByAppendingFormat:@"?service=Seller.upStatus"];
        NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"goodsid":goodsId, @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
        NSString *sign = [PublicObj sortString:signdic];

        NSDictionary *dic = @{
                              @"uid":[Config getOwnID],
                              @"token":[Config getOwnToken],
                              @"goodsid":goodsId,
                              @"status":type,
                              @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                              @"sign":sign
                                };

        [WYNetworking postWithUrl:@"Seller.upStatus" Dic:dic Suc:^(int code, id info, NSString *msg) {
            if (code ==0) {
                [MBProgressHUD showError:msg];
                [weakSelf.commodityTable.mj_header beginRefreshing];
                [weakSelf requstGoodNum];
            }else{
                [MBProgressHUD showError:msg];
            }

            } Fail:^(id fail) {
                
         }];
    }];
    [sure setValue:Pink_Cor forKey:@"_titleTextColor"];
    [cancel setValue:[UIColor grayColor] forKey:@"_titleTextColor"];
    [alertControl addAction:cancel];
    [alertControl addAction:sure];
    [self presentViewController:alertControl animated:YES completion:nil];
}

#pragma mark-------编辑商品-------------
-(void)editGoods:(NSString*)goodsId andType:(NSString *)type{
    if ([type isEqual:@"1"]) {
        AddGoodsVC *vc = [[AddGoodsVC alloc]init];
        vc.fromWhere = @"seller";
        vc.goodsID = goodsId;
        [[YBBaseAppDelegate sharedAppDelegate] pushViewController:vc animated:YES];

    }else{
        AddCommodityVC *edit = [[AddCommodityVC alloc]init];
        edit.fromWhere = @"seller";
        edit.goodsID = goodsId;
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:edit animated:YES];
    }
}
@end
